#include <sys/stat.h>
#include <sys/types.h>
#include "CKEngineLog.h"
#include <iostream>


namespace K_Engine
{
	void CKEngineLog::SetPath(const std::string strPath)
	{
		if(bPathIsExist(strPath))
		{
			// 路径存在
			m_strPath = strPath;
		}
		else
		{
			//路径不存在
			//置为"."
			m_strPath = ".";
		}
	}
	
	
	bool CKEngineLog::bPathIsExist(const std::string& strPath)
	{
		bool isExist = false;
#ifdef _WIN32
		struct _stat fileStat;
		if ((_stat(strPath.c_str(), &fileStat) == 0) && (fileStat.st_mode & _S_IFDIR))
		{
			isExist = true;
		}
#else
		struct stat fileStat;
		if ((stat(strPath.c_str(), &fileStat) == 0) && S_ISDIR(fileStat.st_mode))
		{
			isExist = true;
		}
#endif
		return isExist;
	}
	
	
	CKEngineLog::CKEngineLog(const std::string strPath, LOG_TIME nType)
	{
		SetPath(strPath);
		m_strLastName = "";
		m_nType = nType;
	}
	
	
	CKEngineLog::~CKEngineLog()
	{
	}
	
	
	const std::string& CKEngineLog::GetPath()
	{
		return m_strPath;
	}
	
	
	void CKEngineLog::Log(const std::string& strText, LOG_TYPE level)
	{
		std::lock_guard<std::mutex> lock(m_mutex);
		char temp[11];
		static const char szFormatData[3][10] = {"%Y", "%Y-%m", "%Y-%m-%d"};
		time_t now;
		now = time(NULL);
		strftime(temp, 10, szFormatData[m_nType], localtime(&now));
		if( m_strLastName != temp)
		{
			//文件名不对，更换文件名
			std::string strTemp = m_strPath + "/" + temp + ".log";
			SetFileName(strTemp);
			m_strLastName = temp;
		}
		if(!bOpenFile())
		{
			return;
		}
		WriteLog(strText, level);
	}
}